import {register, login, test, logout, getUserInfo} from "@/api/auth";
import {getToken, removeToken, setToken} from "@/utils/auth";
import {click} from "@/api/game";
import {record} from "@/api/user";


const user = {
  state: {
    token: getToken(),
    username: '',
    nickname: '',
    points: '',
    extraCount: '',
    freeCount: ''
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_USER: (state, userInfo) => {
      state.username = userInfo.username
      state.nickname = userInfo.nickname
      state.points = userInfo.points
      state.extraCount = userInfo.extraCount
      state.freeCount = userInfo.freeCount
    }
  },

  actions: {
    GetUserInfo({commit})  {
      return new Promise((resolve, reject) => {
        getUserInfo().then(res => {
          setUserInfo(res, commit)
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },
    LogOut({commit}) {
      return new Promise((resolve, reject) => {
        logout().then(res => {
          logOut(commit)
          resolve()
        }).catch(error => {
          logOut(commit)
          reject(error)
        })
      })
    },
    Register({ commit }, userInfo) {
      // const rememberMe = userInfo.rememberMe
      return new Promise((resolve, reject) => {
        register(userInfo.username, userInfo.password, userInfo.code, userInfo.uuid).then(res => {
          console.log("注册成功")
          setToken(res.token)
          setUserInfo(res, commit)
          commit('SET_TOKEN', res.token)
          resolve()
        }).catch(error => {
          console.log("注册异常")
          reject(error)
        })
      })
    },
    Login({commit}, userInfo) {
      // const rememberMe = userInfo.rememberMe
      return new Promise((resolve, reject) => {
        login(userInfo.username, userInfo.password, userInfo.code, userInfo.uuid).then(res => {
          setToken(res.token)
          setUserInfo(res, commit)
          commit('SET_TOKEN', res.token)
          // TODO 是否要设置 SET_REMEMBER_ME_TOKEN 的commit
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    }
  },
  Test({commit}, userInfo) {
    return new Promise((resolve, reject) => {
      test().then(res => {
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  }
}

export const logOut = (commit) => {
  commit('SET_TOKEN', '')
  removeToken()
}

export const setUserInfo = (res, commit) => {
  commit('SET_USER', res.user)
}

export default user
